package org.fast.cms.service.common.impl;

import java.util.List;

import org.fast.cms.common.domain.response.LabelValueBean;
import org.fast.cms.common.enums.DictEnum;
import org.fast.cms.common.enums.IsDeletedEnum;
import org.fast.cms.entity.admin.SysDict;
import org.fast.cms.entity.admin.SysDictExample;
import org.fast.cms.persistent.mapper.admin.SysDictMapper;
import org.fast.cms.service.common.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

@Service
public class DictServiceImpl implements DictService {

	@Autowired
	private SysDictMapper dicMapper;

	/**
	 * 判断内容是否存在
	 * @param typeEnum
	 * @param intValue
	 * @return
	 */
	@Override
	@Cacheable(value="dictItemExistsCache")
	public boolean isDictExists(DictEnum typeEnum, Integer intValue) {

		SysDictExample dicExample = new SysDictExample();
		dicExample.createCriteria().andTypeEqualTo(typeEnum.getValue())
			.andValueIntEqualTo(intValue)
			.andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getKey());
		int count = dicMapper.countByExample(dicExample);
		
		return count>0 ? true:false;
	}

	/**
	 * 取得字典列表
	 * @param typeEnum
	 * @return
	 */
	@Override
	@Cacheable(value="dictListCache")
	public List<LabelValueBean> getDictByType(DictEnum typeEnum) {
		SysDictExample dicExample = new SysDictExample();
		dicExample.createCriteria().andTypeEqualTo(typeEnum.getValue())
			.andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getKey());
		dicExample.setOrderByClause("sort asc");
		List<SysDict> lisDict = dicMapper.selectByExample(dicExample);

		List<LabelValueBean> list = Lists.newArrayList();
		for (SysDict d : lisDict) {
			LabelValueBean bean = new LabelValueBean();
			bean.setLabel(d.getLabel());
			bean.setValue(d.getValueInt());
			list.add(bean);
		}
		return list;
	}

	/**
	 * 取得字典
	 * @param typeEnum
	 * @param intValue
	 * @return
	 */
	@Override
	@Cacheable(value="dictItemCache")
	public LabelValueBean getDict(DictEnum typeEnum, Integer intValue) {
		
		if (null == intValue) {
			return new LabelValueBean();
		}
		
		SysDictExample dicExample = new SysDictExample();
		dicExample.createCriteria().andTypeEqualTo(typeEnum.getValue())
				.andValueIntEqualTo(intValue)
				.andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getKey());
		List<SysDict> lisDict = dicMapper.selectByExample(dicExample);

		LabelValueBean bean = new LabelValueBean();
		if (lisDict.size() > 0) {
			bean.setLabel(lisDict.get(0).getLabel());
			bean.setValue(lisDict.get(0).getValueInt());
			bean.setValueStr(lisDict.get(0).getValueStr());
			return bean;
		}
		return bean;
	}


}
